package rd.hardcore.web.controls 
{
	import aze.motion.easing.Back;
	import aze.motion.easing.Elastic;
	import aze.motion.easing.Quadratic;
	import aze.motion.eaze;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.utils.ByteArray;
	import org.audiofx.mp3.MP3FileReferenceLoader;
	import org.audiofx.mp3.MP3SoundEvent;
	
	/**
	 * ...
	 * @author Romain
	 */
	public class PlayPause extends PlayPause_FC
	{
		static public const START_SOUND	: String = "start_sound";
		static public const CLOSE_SOUND	: String = "close_sound";
		
		
		static public var isplaying 		: Boolean;
		private var loader			: MP3FileReferenceLoader;
		private var isReady			: Boolean;
		private var sound			: Sound;
		private var channel			: SoundChannel;
		
		public function PlayPause() 
		{
			mouseChildren = false;
			buttonMode = true;
			
			channel = new SoundChannel();
			
			alpha = 0;
			x = 40;
			y = 40;
			
			scaleX = scaleY = .8;
		}
		
		public function preload( data : ByteArray ) : void
		{
			loader=new MP3FileReferenceLoader();
			loader.addEventListener(MP3SoundEvent.COMPLETE,mp3LoaderCompleteHandler);
			loader.mp3Parser.loadMP3( data );
			
		}
		
		private function mp3LoaderCompleteHandler(e:MP3SoundEvent):void 
		{
			sound = e.sound;
			isReady = true;
		}
		
		private function soundPlayComplete(e:Event):void 
		{
			trace("sound complete");
			channel.removeEventListener(Event.SOUND_COMPLETE, soundPlayComplete);
			stopSound();
		}
		
		/* Play Sound */
		private function playSound( ) : void
		{
			if (!isReady) return;
			
			dispatchEvent(new Event(START_SOUND, true));
			
			channel = sound.play();
			channel.addEventListener(Event.SOUND_COMPLETE, soundPlayComplete);
			gotoAndStop(2);
		}
		
		private function stopSound() : void
		{
			gotoAndStop(1);
			channel.stop();
			isplaying = false;
			dispatchEvent(new Event(CLOSE_SOUND, true));
		}
		
		public function handleClick(e:MouseEvent):void 
		{
			isplaying = !isplaying;
			
			if (isplaying)
				playSound();
			else
				stopSound();
			
		}
		
		public function handleOver(e:MouseEvent):void 
		{
			eaze(this).to( .4, { alpha:1, scaleX:1, scaleY:1 } )
				.easing(Back.easeOut);
		}
		
		public function handleOut(e:MouseEvent):void 
		{
			if (isplaying) return;
			
			eaze(this).to( .3, { alpha:0, scaleX:.8, scaleY:.8 } )
				.easing(Quadratic.easeIn);
		}
		
	}

}